package com.wfg.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wfg.blog.dao.mapper.ArticleMapper;
import com.wfg.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {
    /**
     * 在线程池 执行 不会影响原有的主线程
     */
    @Async("taskExecutor")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
//        int viewCounts = article.getViewCounts();
//        Article articleUpdated = new Article();
//        articleUpdated.setViewCounts(viewCounts + 1);
//        System.out.println(articleUpdated.getViewCounts() + " views");
//        LambdaUpdateWrapper<Article> updateWrapper = new LambdaUpdateWrapper();
//        updateWrapper.eq(Article::getId,article.getId());
//        //设置一个 为了在多线程的环境 线程安全
//        updateWrapper.eq(Article::getViewCounts,article.getViewCounts());
//        //UPDATE ms_article SET comment_counts=?, view_counts=?, weight=?, view_counts=? WHERE (id = ?)
//        articleMapper.update(articleUpdated,updateWrapper);

        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(article.getViewCounts() + 1);
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getId,article.getId());
        queryWrapper.eq(Article::getViewCounts,article.getViewCounts());
        articleMapper.update(articleUpdate,queryWrapper);
        //UPDATE ms_article SET  view_counts=?,  WHERE (id = ? AND view_counts = ?)
//        try {
//            Thread.sleep(5000);
//            System.out.println("完成更新");
//
//
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
    }
}
